package blue.blog.util;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.blue.core.dict.UploadType;
import com.blue.crawler.engine.FileModel;
import com.blue.crawler.engine.ListDetailModel;

import blue.blog.core.model.CmsDoc;
import blue.blog.core.model.CmsDocFile;

public class CmsDocConvertor
{
	private CmsDocConvertor()
	{
	}
	
	public static CmsDoc toDoc(ListDetailModel model, Integer channelId)
	{
		if (model == null)
			return null;
		
		CmsDoc doc = new CmsDoc();
		doc.setChannelId(channelId);
		doc.setTitle(model.getTitle());
		doc.setSummary(model.getSummary());
		doc.setContent(model.getContent());
		doc.setCreateTime(model.getCreateTime());
		doc.setUrl(model.getUrl());
		
		List<CmsDocFile> docFileList = new ArrayList<>();
		int size = 0;
		int files = 0;
		FileModel coverFile = model.getCoverFile();
		if (coverFile != null)
		{
			doc.setCover(coverFile.getThumbPath());
			CmsDocFile docFile = toDocFile(coverFile, doc.getCreateTime(), 1);
			docFileList.add(docFile);
		}
		if (model.getFileList() != null && !model.getFileList().isEmpty())
		{
			for (FileModel fileModel : model.getFileList())
			{
				CmsDocFile docFile = toDocFile(fileModel, doc.getCreateTime(), 0);
				docFileList.add(docFile);
				files++;
				size += docFile.getSize();
			}
		}
		doc.setFiles(files);
		doc.setFileSize(size);
		doc.setFileList(docFileList);
		
		return doc;
	}
	
	public static CmsDocFile toDocFile(FileModel model, LocalDateTime createTime, Integer state)
	{
		if (model == null)
			return null;
		
		CmsDocFile docFile = new CmsDocFile();
		docFile.setName(model.getName());
		docFile.setPath(model.getPath());
		docFile.setThumbPath(model.getThumbPath());
		docFile.setSize(model.getSize());
		docFile.setUploadTime(createTime);
		docFile.setMimeType(model.getMimeType());
		docFile.setState(state);
		
		if (model.getType() != null)
			docFile.setType(model.getType().getIndex());
		else
			docFile.setType(UploadType.UNKNOWN.getIndex());
		
		return docFile;
	}
	
}
